package com.me.web;

import com.me.dao.IPetDao;
import com.me.dao.IUserDao;
import com.me.dao.IVisitDao;
import com.me.dao.impl.PetDao;
import com.me.dao.impl.UserDao;
import com.me.dao.impl.VisitDao;
import com.me.domain.Pet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@MultipartConfig
@WebServlet("/petmanage")
public class PetServlet extends BaseServlet{
    @Override
    protected void doGet() throws ServletException, IOException {
        String m = getParam("m");
	    if (m == null) {
		    showAll();
	    } else if(m.equals("my")){
		    showMy();
	    } else if (m.equals("detail")) {
	    	detail();
	    } else if (m.equals("add")) {
		    addPage();
	    } else if (m.equals("edit")) {
		    edit();
	    } else if (m.equals("del")) {
	    	delete();
	    }
    }

	private void edit() throws ServletException, IOException {
		PetDao pdao = new PetDao();
		UserDao udao = new UserDao();
		String id = getParam("id");
		Pet pet = pdao.getById(id);
		pet.setOwner(udao.getById(pet.getOwnerId()));
		setReqAttr("users", udao.getAll());
		setReqAttr("pet", pet);
		forward("/admin/petedit.jsp");
	}



	private void addPage() throws ServletException, IOException {
		UserDao udao = new UserDao();
		setReqAttr("users", udao.getAll());
		forward("/admin/petadd.jsp");
	}

	private void showMy() throws ServletException, IOException {
		PetDao pdao = new PetDao();
		setReqAttr("pets",pdao.getPetsByOwnerId(getSesUser().getId()));
		forward("/pet/mypet.jsp");
	}


	private void detail() throws ServletException, IOException {
		IPetDao pdao = new PetDao();
		IVisitDao vdao = new VisitDao();
		String id = getParam("id");
		Pet pet = pdao.getById(id);
		setReqAttr("pet",pet);
		setReqAttr("vists",vdao.getVisitsByPetId(pet.getId()));
		forward("/pet/petdetail.jsp");
	}

	private void showAll() throws ServletException, IOException {
		PetDao pdao = new PetDao();
		UserDao udao = new UserDao();
		List<Pet> pets = pdao.getAll();
		for (Pet p : pets) {
			p.setOwner(udao.getById(p.getOwnerId()));
		}
		setReqAttr("pets", pets);
		forward("/admin/petmanage.jsp");
	}

    @Override
    protected void doPost() throws ServletException, IOException {
        String m = getParam("m");
        if (m.equals("add")){
            add();
        } else if (m.equals("search")) {
	        search();
        } else if (m.equals("edit")) {
	        update();
        }
    }

	private void update() throws ServletException, IOException {
		try {
			IUserDao udao = new UserDao();
			IPetDao pdao = new PetDao();
			Part part = getPart("photo");
			String id = getParam("id");
			Pet pet = pdao.getById(id);
			String filename = getFileName(part);
			String photo = null;
			if (filename!=null){
				long currentTimeMillis = System.currentTimeMillis();
				photo = "img/"+currentTimeMillis+filename.substring(filename.lastIndexOf("."));
				filename = getServletContext().getRealPath("/")+"/"+photo;
				part.write(filename);
				pet.setPhoto(photo);
			}
			pet.setName(getParam("name"));
			pet.setBirthdate(getParam("birth"));
			String ownerName = getParam("owner");
			pet.setOwnerId(udao.getByName(ownerName).getId());
			pdao.update(pet);
			if (getParam("detail") != null) {
				forward("./petmanage?m=detail&id=" + pet.getId());
			} else {
				forward("./petmanage");
			}
		}catch (Exception e){
			setReqAttr("msg",e.getMessage());
			forward("/admin/petedit.jsp");
		}
	}

	private void search() throws ServletException, IOException {
		IPetDao pdao = new PetDao();
		String customerName = getParam("customerName");
		String petName = getParam("petName");

		List<Pet> pets = pdao.search(customerName, petName);

		setReqAttr("pets", pets);
		forward("/admin/petmanage.jsp");
	}

	private void add() throws ServletException,IOException{
        try {
	        IUserDao udao = new UserDao();
            Part part = getPart("photo");
            String filename = getFileName(part);
            String photo;
            if (filename!=null){
                long currentTimeMillis = System.currentTimeMillis();
                photo = "img/"+currentTimeMillis+filename.substring(filename.lastIndexOf("."));
                filename = getServletContext().getRealPath("/")+"/"+photo;
                part.write(filename);
            }else {
                photo="/img/123.jpg";
            }
            Pet pet = new Pet();
            pet.setName(getParam("name"));
            pet.setBirthdate(getParam("birth"));
            pet.setPhoto(photo);
            String ownerName = getParam("owner");
            pet.setOwnerId(udao.getByName(ownerName).getId());
            PetDao petDao = new PetDao();
            petDao.save(pet);
            setReqAttr("msg","添加成功");
            forward("./petmanage?m=detail&id=" + pet.getId());
        }catch (Exception e){
            setReqAttr("msg",e.getMessage());
            forward("/admin/petadd.jsp");
        }
    }
    private String getFileName(Part part){
        String cotentDesc = part.getHeader("content-disposition");
        String fileName = null;
        Pattern pattern = Pattern.compile("filename=\".+\"");
        Matcher matcher = pattern.matcher(cotentDesc);
        if (matcher.find()){
            fileName = matcher.group();
            fileName = fileName.substring(10,fileName.length()-1);
        }
        return fileName;
    }
    private void delete() throws ServletException,IOException{
        try {
            int petId = Integer.parseInt(getParam("id"));
            PetDao petDao = new PetDao();
            petDao.delete(petId);
            setReqAttr("msg","删除成功");
            forward("./petmanage");
        }catch (Exception e){
	        System.out.println(e.getMessage());
        }
    }
}
